//
//  WLWebViewController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/10.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import<WebKit/WebKit.h>
#import "WLWebViewController.h"
//#import "WKWebViewJavascriptBridge.h"
//#import "NJKWebViewProgress.h"
//#import "NJKWebViewProgressView.h"

@interface WLWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

@property (nonatomic,strong) WKWebViewConfiguration *configuration;
@property (nonatomic,strong) WKWebView *wkWebView;
//@property (nonatomic, strong) WebViewJavascriptBridge *bridge;

@property (nonatomic, strong) UIProgressView *progressView;//设置加载进度条

@end

@implementation WLWebViewController

- (void)dealloc {
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
//    [self.wkWebView removeObserver:self forKeyPath:@"title"];
//    NSURL * url =[NSURL URLWithString:@""];
//    NSURLRequest *request =[NSURLRequest requestWithURL:url];
//    [self.wkWebView loadRequest:request];
    [_configuration.userContentController removeScriptMessageHandlerForName:@"TianYiLianJs"];
}
- (void)messageReaded
{
    //    WLWkSelf
    NSDictionary *params = @{@"id":@(self.msgId)};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/set/haslook" withParamsDic:params success:^(NSDictionary *successDict) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kHasReadedMessageNofication object:nil];
        NSInteger unreadNum = [[NSUserDefaults standardUserDefaults] integerForKey:UNREAD_MSG_NUM];
        if (unreadNum-1>0) {
            [[NSUserDefaults standardUserDefaults] setInteger:unreadNum-1 forKey:UNREAD_MSG_NUM];
        }
        else
        {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:UNREAD_MSG_NUM];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        
    } error:^(NSError *error) {
        
    } inView:nil];
}
- (NSInteger)msgId {
    if (_msgId == 0) {
        _msgId = -1;
    }
    return _msgId;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.fd_interactivePopDisabled = YES;
    self.title = self.titleStr;
    if (self.msgId >= 0) {
        [self messageReaded];
    }
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    backButton.frame = CGRectMake(0, 0, 50, 44);
    [backButton setImage:[UIImage imageNamed:@"arrow_back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(webBackButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBar;
    
    
    _configuration = [[WKWebViewConfiguration alloc] init];
    _configuration.allowsInlineMediaPlayback = YES;
    _configuration.mediaPlaybackRequiresUserAction = NO;
    WKUserContentController *userController = [[WKUserContentController alloc] init];
    _configuration.userContentController = userController;
    [userController addScriptMessageHandler:self name:@"TianYiLianJs"];
    [userController addScriptMessageHandler:self name:@"TianYiL"];
    
    
    _wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:_configuration];
    _wkWebView.allowsBackForwardNavigationGestures = YES;
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    [self.wkWebView loadRequest:request];
    self.wkWebView.UIDelegate = self;
    self.wkWebView.navigationDelegate = self;
    [self.view addSubview:self.wkWebView];
    WLWkSelf
    [_wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    [self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    
    
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, 2)];
    _progressView.trackTintColor = wlBackColor;
    //设置进度条上进度的颜色
    self.progressView.progressTintColor = [UIColor blueColor];
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view addSubview:self.progressView];
}

- (void)shareAction {
    //分享的标题
    NSString *textToShare = @"分享的标题。";
    //分享的图片
    UIImage *imageToShare = [UIImage imageNamed:@"312.jpg"];
    //分享的url
    NSURL *urlToShare = [NSURL URLWithString:@"http://www.baidu.com"];
    //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
    NSArray *activityItems = @[textToShare,imageToShare, urlToShare];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    //不出现在活动项目
    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"completed");
            //分享 成功
        } else  {
            NSLog(@"cancled");
            //分享 取消
        }
    };
    
}
- (void)webBackButtonAction
{
    if ([self.wkWebView canGoBack])
    {
        [self.wkWebView goBack];
    }
    else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 监听
/*
 *4.在监听方法中获取网页加载的进度，并将进度赋给progressView.progress
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    //加载进度值
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        if (object == self.wkWebView)
        {
            [self.progressView setProgress:self.wkWebView.estimatedProgress animated:YES];
            if(self.wkWebView.estimatedProgress >= 1.0f)
            {
                /*
                 *添加一个简单的动画，将progressView的Height变为1.4倍
                 *动画时长0.25s，延时0.3s后开始动画
                 *动画结束后将progressView隐藏
                 */
                __weak typeof (self)weakSelf = self;
                [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                    weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
                } completion:^(BOOL finished) {
                    weakSelf.progressView.hidden = YES;
                    
                }];
            }
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKWKNavigationDelegate Methods
/*
 * 在WKWebViewd的代理中展示进度条，加载完成后隐藏进度条
 */
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    //加载完成后隐藏progressView
    self.progressView.hidden = YES;
    if (self.titleStr==nil) {
        self.title = self.wkWebView.title;
    }
    // 禁止放大缩小
//    NSString *injectionJSString = @"var script = document.createElement('meta');"
//    "script.name = 'viewport';"
//    "script.content=\"width=device-width, initial-scale=0,maximum-scale=0, minimum-scale=0, user-scalable=no\";"
//    "document.getElementsByTagName('head')[0].appendChild(script);";
//    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.hidden = YES;
    
    // 如果请求被取消
    if (error.code == NSURLErrorCancelled) {
        return;
    }
}

// 当Web视图的Web内容进程终止时调用。
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    self.progressView.hidden = YES;
}

//JS调用的OC回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
    if ([message.name isEqualToString:@"TianYiLianJs"]) {
        NSDictionary *dictImage = message.body;
        if ([dictImage[@"type"] isEqualToString:@"invite"]) {
            [self shareInviteImageAction:dictImage[@"image"]];
        }
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"JS调用的OC回调方法" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleCancel handler:nil];
//        [alert addAction:action];
//        [self presentViewController:alert animated:YES completion:nil];
    }
}
// 交互。可输入的文本。
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler
{
    NSString *appVersion = [WLCommonTool getAppVersion];
    completionHandler(appVersion);//这里就是要返回给JS的返回值
}

/*
//页面跳转 类似UIWebView的 -webView: shouldStartLoadWithRequest: navigationType:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *urlString = navigationAction.request.URL.absoluteString;
    NSURL *url = navigationAction.request.URL;
    
    if ([urlString rangeOfString:@"about:blank"].location != NSNotFound) {
        //不允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    
    //打电话
    NSString *scheme = [url scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [url resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"tel://%@", resourceSpecifier];
        /// 解决iOS10及其以上系统弹出拨号框延迟的问题
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
            // 10及其以上系统
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        } else {
            // 10以下系统
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        }
        //不允许跳转
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    //获取对应的方法
    NSRange urlRange = [urlString rangeOfString:@"mlc://"];
    
    if (urlRange.length != NSNotFound && urlRange.location != NSNotFound) {
        NSString *methodStr = [urlString substringFromIndex:(urlRange.location + urlRange.length)];
        NSString *codeStr = [methodStr stringByRemovingPercentEncoding];
        NSArray *contentArray = [codeStr componentsSeparatedByString:@"?"];
        NSString *method = contentArray.firstObject;
        SEL selctor = NSSelectorFromString(method);
        if ([self respondsToSelector:selctor]) {
            //获取内容
            
            //执行方法
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [self performSelector:selctor];
#pragma clang diagnostic pop
            
            //不允许跳转
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    
}
*/

- (void)shareInviteImageAction:(NSString *)imgUrl
{
    if (imgUrl != nil)
    {
        [self showHUDProgressHUD];
        WLWkSelf
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *dataImg = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
            UIImage *imageShare = [UIImage imageWithData:dataImg];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideHUD];
                NSArray *activityItems = @[imageShare];//@[textToShare,imageToShare,urlToShare];
                UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
                //不出现在活动项目
                activityVC.excludedActivityTypes = @[UIActivityTypeAirDrop];
                [weakSelf presentViewController:activityVC animated:YES completion:nil];
                // 分享之后的回调
                activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
                    if (completed) {
                        WLLog(@"completed");
                        //分享 成功
                    } else  {
                        WLLog(@"cancled");
                        //分享 取消
                    }
                };
            });
        });
    }
    return;
    
//    NSString *textToShare = @"分享的标题。";
//    //分享的图片
//    UIImage *imageToShare = [UIImage imageNamed:@"page_6_1.jpg"];
//    //分享的url
//    NSURL *urlToShare = [NSURL URLWithString:@"http://47.75.195.106/router/upload//file/dir/img_6497dcd8077343e8ac0f256dbb15615c.png"];
//    //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
//    NSArray *activityItems = @[textToShare,imageToShare,urlToShare];
//    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    //不出现在活动项目
//    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
